package com.iflytek.springboot_medicine.service.impl;

import com.iflytek.springboot_medicine.entity.Income;
import com.iflytek.springboot_medicine.pojo.IncomePojo;
import com.iflytek.springboot_medicine.service.CategoryRepository;
import com.iflytek.springboot_medicine.service.IncomeRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class IncomeServiceImpl {
    private final IncomeRepository incomeRepository;
    private final CategoryRepository categoryRespository;

    public IncomeServiceImpl(IncomeRepository incomeRepository, CategoryRepository categoryRespository) {
        this.incomeRepository = incomeRepository;
        this.categoryRespository = categoryRespository;
    }

    /**
     *  Page<Income> 转换为 Page<IncomePojo>
     * @param name
     * @param startDate
     * @param endDate
     * @param pageable
     * @return
     */
    public Page<IncomePojo> findStockInsByCategoryAndDateRange(String name, Date startDate, Date endDate, Pageable pageable) {
        Page<Income> byCategoryAndDateRange = incomeRepository.findByCategoryAndDateRange(name, startDate, endDate, pageable);
        System.out.println(byCategoryAndDateRange);
        return byCategoryAndDateRange.map(IncomePojo::new);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Pageable findIncome(int pageNum, int pageSize) {
        // 构建分页请求
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        // 执行分页查询
        return pageable;
    }

    /**
     * 根据类别查找ID
     * @param catyName
     * @return
     */
    public int selectByName(String catyName) {
        int byName = categoryRespository.findIdByName(catyName);
        return byName;
    }


    /**
     * 删除入库信息
     * @param id
     * @return
     */
    public Income deleteIncomeById(int id) {
        return incomeRepository.deleteById(id);
    }

    /**
     * 批量删除入库信息
     */
    public void deleteAllInBatch(List<Integer> ids) {
        incomeRepository.deleteAllByIdInBatch(ids);
    }

    /**
     * 存储更新的Income
     * @param income
     * @return
     */
    public Income saveIncome(Income income) {
        System.out.println(income);
        return incomeRepository.save(income);
    }

    /**
     * 入库新信息
     * @param income
     * @return
     */
    public Income addIncome(Income income) {
        return incomeRepository.save(income);
    }

}
